﻿using System;
using System.Diagnostics;
using System.IO;

namespace CXW.Core
{
    /// <summary>
    /// Represents a versioned reference to an AddIn. Used by <see cref="AddInManifest"/>.
    /// </summary>
    public class AddInReference
    {
        /// <remark/>     
        static Version entryVersion;

        internal static Version ParseVersion(string version, string hintPath)
        {
            if (version == null || version.Length == 0)
                return new Version(0, 0, 0, 0);
            if (version.StartsWith("@"))
            {
                if (version == "@SharpDevelopCoreVersion")
                {
                    if (entryVersion == null)
                        entryVersion = new Version(RevisionClass.Major + "." + RevisionClass.Minor + "." + RevisionClass.Build + "." + RevisionClass.Revision);
                    return entryVersion;
                }
                if (hintPath != null)
                {
                    string fileName = Path.Combine(hintPath, version.Substring(1));
                    try
                    {
                        FileVersionInfo info = FileVersionInfo.GetVersionInfo(fileName);
                        return new Version(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart);
                    }
                    catch (FileNotFoundException ex)
                    {
                        throw new CoreException("Cannot get version '" + version + "': " + ex.Message);
                    }
                }
                return new Version(0, 0, 0, 0);
            }
            else
            {
                return new Version(version);
            }
        }
    }
}
